package store.lunangangster.engine.impl.cmd;

import store.lunangangster.engine.NodeFlowException;
import store.lunangangster.engine.impl.interceptor.CommandContext;

public class HistoryDeleteCmd implements Command<Void> {

  protected String id;
  protected String processInstanceId;
  protected String processDefinitionId;

  protected String processInstanceName;
  protected String processDefinitionName;

  public HistoryDeleteCmd(String id, String processInstanceId, String processDefinitionId) {
    this.id = id;
    this.processInstanceId = processInstanceId;
    this.processDefinitionId = processDefinitionId;
  }

  public HistoryDeleteCmd(String processInstanceName, String processDefinitionName) {
    this.processInstanceName = processInstanceName;
    this.processDefinitionName = processDefinitionName;
  }

  @Override
  public Void execute(CommandContext commandContext) {
    String[] statement = getStatement();
    commandContext.getDbSqlSession().getSqlSession().delete(statement[0], statement[1]);
    return null;
  }

  private String[] getStatement() {
    boolean isIdStatement = id != null || processInstanceId != null || processDefinitionId != null;
    boolean isNameStatement = processInstanceName != null || processDefinitionName != null;

    if (isIdStatement) {
      if (id != null) {
        return new String[] {"deleteHistory", id};
      }
      if (processInstanceId != null) {
        return new String[] {"deleteHistoryByProcessInstanceId", processInstanceId};
      }
      return new String[] {"deleteHistoryByProcessDefinitionId", processDefinitionId};
    } else if (isNameStatement) {
      if (processInstanceName != null) {
        return new String[] {"deleteHistoryByProcessInstanceNameLike", processInstanceName};
      }
      return new String[] {"deleteHistoryByProcessDefinitionNameLike", processDefinitionName};
    } else {
      throw new NodeFlowException("查询参数不能为空");
    }
  }
}
